package com.mucd.chat.socket;

import com.mucd.chat.config.CustomConfigurator;
import com.mucd.chat.service.socketService.OnlineSocketService;
import com.mucd.chat.utils.SocketUtils;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint(value = "/websocket/online", configurator = CustomConfigurator.class)
@Component
@RequestMapping("ws")
@RestController
@Slf4j
public class OnlineSocket {
    @OnOpen
    public void onOpen(Session session) {

        SocketUtils socketUtil = SpringUtils.getBean(SocketUtils.class);
        LoginUser loginUser = socketUtil.getLoginUser(session);

        log.info("用户登录：" + loginUser.getUser().getUserName());


        OnlineSocketService onlineSocketService = SpringUtils.getBean(OnlineSocketService.class);
        onlineSocketService.selectNotReadNum(loginUser, session);
        onlineSocketService.settingOnlineStatus(loginUser, session, true);
    }

    // WebSocket 接收到消息时的操作
    @OnMessage
    public void onMessage(Session mySession, String message, @PathParam("userId") String targetUserId) throws IOException {

    }

    // WebSocket 连接关闭时的操作
    @OnClose
    public void onClose(Session session, @PathParam("userId") String id) throws IOException {
        session.close();

        SocketUtils socketUtil = SpringUtils.getBean(SocketUtils.class);
        LoginUser loginUser = socketUtil.getLoginUser(session);

        OnlineSocketService onlineSocketService = SpringUtils.getBean(OnlineSocketService.class);
        onlineSocketService.settingOnlineStatus(loginUser, session, false);

        log.info("关闭连接");
    }

    // WebSocket 发生错误时的操作
    @OnError
    public void onError(Session session, Throwable throwable) throws IOException {
        log.error("发生错误", throwable);
        session.getBasicRemote().sendText("发生了错误:" + throwable.getMessage());

    }
}
